package com.hiof.moraa.server.service;

import com.hiof.moraa.server.service.model.GeoPoint;
import com.hiof.moraa.server.service.model.GoogleGpsGeoPoint;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Bergy
 */
public class ParseKmlFileService {

    /**
     * The xml file must have only two Placemark that is Bike & Run Each of them
     * have one coordinates node inside And Bike must have before Run
     *
     * @param kmlPath
     * @return
     * @throws Exception
     */
    public List<GeoPoint> parseKmlFile(String kmlPath) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(kmlPath);
        return parseDocument(dom);
    }

    private List<GeoPoint> parseDocument(Document dom) {
        List<GeoPoint> result = new ArrayList<GeoPoint>();
        Element docEle = dom.getDocumentElement();
        NodeList nl = docEle.getElementsByTagName("coordinates");
        if (nl != null && nl.getLength() > 0) {
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                result.addAll(getCoordinatesFromString(node.getFirstChild().getNodeValue()));
            }
        }
        return result;
    }

    private List<GeoPoint> getCoordinatesFromString(String value) {
        List<GeoPoint> result = new ArrayList<GeoPoint>();
        String[] coordinates = value.split("\n");
        for (String string : coordinates) {
            if (!string.trim().equals("")) {
                result.add(convertString2GeoPoint(string.trim()));
            }
        }
        return result;
    }

    private GeoPoint convertString2GeoPoint(String coordinate) {
        String[] values = coordinate.split(",");
        double lat = Double.parseDouble(values[1]);
        double lng = Double.parseDouble(values[0]);
        double alt = Double.parseDouble(values[2]);
        GeoPoint geoPoint = new GoogleGpsGeoPoint(lat, lng, alt);
        return geoPoint;
    }
}
